package edu.zut.main.thread;

public class ThreadMoney {

    public static void main(String[] args) {
        Account account = new Account(100);
        DrawMoneyThread boyDrawMoney = new DrawMoneyThread(account, 30);
        DrawMoneyThread girlDrawMoney = new DrawMoneyThread(account, 60);
        new Thread(boyDrawMoney, "boy").start();
        new Thread(girlDrawMoney, "girl").start();
    }
}

//取钱的线程任务
class DrawMoneyThread implements Runnable {
    private Account account; //账户
    private int drawMoney; //取款额

    public DrawMoneyThread(Account account, int drawMoney) {
        this.account = account;
        this.drawMoney = drawMoney;
    }

    @Override
    public void run() {
        //保证取钱的操作同一时刻，只能由一个线程完成   利用同步代码块将具有原子性的代码同步起来
        synchronized (account) {
            //取钱
            if (account.getMoney() - drawMoney < 0) {
                System.out.println(Thread.currentThread().getName() + "余额不足!!!!");
                return;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.setMoney(account.getMoney() - drawMoney);
            System.out.println(Thread.currentThread().getName() + "消费后剩余：" + account.getMoney());
        }
    }
}

//账户
class Account {

    private int money; //账户余额

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public Account(int money) {
        this.money = money;
    }


}

